package com.huiruan.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huiruan.utils.JwtUtil;
import com.huiruan.utils.Result;
import com.huiruan.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 放行OPTIONS预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        // 2. 获取token
        String authHeader = request.getHeader(jwtUtil.getTokenHeader());
        // 3. 验证token是否存在和格式
        if (authHeader == null) {
            return sendErrorResponse(response,
                    Result.failed(ResultCode.UNAUTHORIZED));
        }

        if (!authHeader.startsWith(jwtUtil.getTokenPrefix())) {
            return sendErrorResponse(response,
                    Result.failed(ResultCode.UNAUTHORIZED));
        }

        // 4. 提取并验证token
        String token = authHeader.replace(jwtUtil.getTokenPrefix(), "").trim();
        try {
            if (jwtUtil.isTokenExpired(token)) {
                return sendErrorResponse(response,
                        Result.failed(ResultCode.UNAUTHORIZED));
            }

            // 5. 设置用户信息
            String username = jwtUtil.getSubjectFromToken(token);
            String userType = jwtUtil.getUserTypeFromToken(token);
            Long userId = jwtUtil.getUserIdFromToken(token);
            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            request.setAttribute("userType", userType);

        } catch (Exception e) {
            return sendErrorResponse(response,
                    Result.failed(ResultCode.UNAUTHORIZED));
        }

        return true;
    }

    /**
     * 发送统一格式的错误响应
     * @param response HttpServletResponse
     * @param result 统一返回结果 {code, message, data}
     * @return 总是返回false表示拦截
     */
    private boolean sendErrorResponse(HttpServletResponse response, Result<?> result) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().println(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue));
        return false;
    }
}
